<template>
  <div class="front">
    <div class="left">
      <el-form :model="inboundForm" ref='inboundRef' label-width="120px">
        <el-form-item class="left-input" label="入库方式" :required="true" style="width: 60%;">
          <el-select v-model="inboundForm.wms_inbound_type" placeholder="请选择入库方式" style="width: 60%;">
            <el-option label="还货入库" value="2" />
            <el-option label="加工入库" value="3" />
            <el-option label="退货入库" value="4" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item class="left-input" label="入库客户" style="width: 60%;" :required="true" >
          <el-select v-model="inboundForm.clientId" placeholder="搜索匹配/扫码" style="width: 60%;">
            <el-option v-for="item in clientList" :key="item.id" :label="item.clientName" :value="item.id" />
          </el-select>
        </el-form-item> -->



        <!--<el-form-item label="选择仓库" :required="true" style="width: 60%;">
          <el-cascader ref="articleOrgRef" v-model="inboundForm.desWarehouseId" :options="storageOptions"
            placeholder="打开选择仓位"
            :props="{ expandTrigger: 'hover', emitPath: false, checkStrictly: true, children: 'storages', value: 'warehouseId', label: 'warehouseName', }"
            @change="cascaderHanlderChange" @expand-change="handleExpandChange" style="width: 60%;" />
        </el-form-item>-->


        
        <el-form-item class="left-input" label="入库数量" style="width: 60%;" :required="true">
          <el-input oninput="value=value.replace(/[^\d]/g,'')" v-model="inboundForm.jadeQuantity" />
        </el-form-item>
      </el-form>
    </div>

    <div class="right">
      <div style="margin: 0 0 10px 0 ;">
        <el-radio-group v-model="labelType" size="small">
          <el-radio-button label="phone">拍照上传</el-radio-button>
          <el-radio-button label="barcode">条形码上传</el-radio-button>
        </el-radio-group>
      </div>
      <div v-if="labelType == 'phone'">
        <div class="right-photo" >
          <video ref="videoElement" class="rigth-video" autoplay></video>
          <canvas ref="canvasElement" class="right-img"></canvas>
        </div>
        <div class="right-action">
          <el-upload action="http://8.134.106.197:9001/common/uploadImage" class="upload"
            :headers="{ Authorization: token }" :show-file-list="false" accept=".png,.jpg,.jpeg,.webp"
            style="display: inline-block;" :name="file" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
            :on-error="console.log(error)" :on-success="handleUpload">
            <el-button @click="uploadImg" style="color:#1890ff;">上传</el-button>
          </el-upload>
          <el-button @click="takePhoto" style="color:#1890ff;margin-left: 10px;">拍照</el-button>
          <el-button @click="triggerCamera" style="color:#1890ff;">{{ cameraActive ? '关闭摄像头' : '打开摄像头' }}</el-button>
        </div>
      </div>
      <div v-if="labelType == 'barcode'">
        <el-form :label-position="left" label-width="80px" :model="formLabelAlign">
          <el-form-item label="条形码">
            <el-input style="width: 240px;"></el-input>
          </el-form-item>
        </el-form>
      </div>

    </div>
  </div>

  <div class="tail">
    <div class="tail-action">
      <el-button type="primary" @click="onSubmit">操作入库</el-button>
      <el-popover placement="bottom" trigger="click">
        <template #reference>
          <el-button><el-icon>
              <List />
            </el-icon>显示设置</el-button>
        </template>
        <el-checkbox-group v-model="selectedFilters.data">
          <el-checkbox v-for="item in tableFilter.data" :label="item.label" @change="filterColumns"
            :disabled="item.isdisabled" />
        </el-checkbox-group>
      </el-popover>
    </div>
    <el-table :data="tableData()" border style="width: 100%" max-height="320">
      <template v-slot:empty>
        <div class="no-data">暂无数据</div>
      </template>
      <el-table-column label="货品图片" width="90">
        <template #default="scope">
          <el-image :src="'http://47.106.116.146:8080/profile' + scope.row.imageUrl" fit="contain"
            style="max-height: 50px;max-width: 30px;" :preview-teleported="true" :lazy="true"
            :preview-src-list="imgPreview" @click="previewSrcList(scope.row.imageUrl)"></el-image>
        </template>
      </el-table-column>
      <el-table-column v-for="item in inboundJadeDataColumn.data" :prop="item.prop" :min-width="item.minWidth"
        :width="item.width" :max-width="item.maxWidth" :label="item.label" />
      <el-table-column label="操作" width="80" fixed="right">
        <template #default>
          <!-- <el-button link type="primary" size="small" @click="delete(row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination v-model:current-page="data.page" v-model:page-size="data.limit"
        layout="prev, pager, next ,total,sizes" :total="data.total" @current-change="handleCurrentChange"
        @size-change="handleSizeChange" />
    </div>
  </div>


  <div class="dialog-list">
    <el-dialog v-model="dialogVisibleResult" title="检测结果" :close-on-press-escape="true" :close-on-click-modal="true"
      @close="handleCloseResult()" style="width: 350px;">
      <el-table :data="imageUrlList" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="40" />
        <el-table-column label="出库对象" prop="url" width="120">
          <template #default="scope">
            <el-image :src="'http://47.106.116.146:8080/profile' + scope.row.imageUrl" alt="Photo" fit="contain"
              style="max-height: 120px;max-width: 70px;" :preview-teleported="true" :lazy="true"
              :preview-src-list="imgPreview" @click="previewSrcList(scope.row.url)"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="库存对比" prop="matchUrl">
          <template #default="scope">
            <!-- <el-tooltip content="查无此货">
            </el-tooltip> -->
            <el-image :src="'http://47.106.116.146:8080/profile' + scope.row.matchUrl" alt="Photo" fit="contain"
              style="max-height: 120px;max-width: 70px;" :preview-teleported="true" :lazy="true"
              :preview-src-list="imgPreview" @click="previewSrcList(scope.row.matchUrl)">
              <template v-slot:error>
                <i class="image-miss">{{ match_controll }}</i>
              </template>
            </el-image>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" style="margin-top: 15px;" @click="ensureJade">确认</el-button>
      <div>请勾选需要入库的对象然后选择确认</div>
    </el-dialog>
  </div>
</template>

<script>
import { onBeforeMount, onMounted, toRefs, reactive, ref, defineComponent, watch } from 'vue';
import { ElMessage, } from 'element-plus';
import { Plus, QuestionFilled, Close, List } from '@element-plus/icons-vue';
import { getToken } from '@/utils/auth'
import { inbounding } from '@/api/inbound/inbound'
import { getJadeCrop, jadeMatch, getJadeFeature, getJadeInfo, } from '@/api/outbound/outbound'
import { getWarehouseListV2, getStorageCascader } from '@/api/setting/setting';
import { getClientList } from "@/api/user/user"
import axios from 'axios'

export default defineComponent({
  name: 'loginAccount',
  components: {
    Plus,
    QuestionFilled,
    Close,
    List
  },
  setup() {
    const inboundRef = ref()
    const videoElement = ref(null)
    const webcam = ref(null)
    const canvasElement = ref(null)
    const cameraActive = ref(false)
    const videoStream = ref(null)
    const dialogImageUrl = ref('')
    const match_controll = ref('识别中')
    const rate = ref(2.0)
    const magnification = ref(2.0)//倍率控制
    const operation = ref('floor')
    const token = ref('')
    const dialogVisibleImg = ref(false)
    const inboundOrderCode = ref(1)
    const imageUrlList = ref([])
    const storageOptions = ref([])
    const imgPreview = ref([])
    const treeList = ref([])
    //表格的全数据（这里是自定义的列表，要看分页效果自行往此数组内加数据）
    const inboundJadeInfoData = ref([])
    const inboundJadeDataColumn = reactive({
      data: [
      ]
    })
    const selectedFilters = reactive({
      data: []
    })
    const tableFilter = reactive({//表头自定义数组
      data: [
        { label: '货品条码', prop: 'jadeBarcode', width: '200', isdisabled: true, isSelected: true },
        { label: '入库单单号', prop: 'orderCode', width: '200', isdisabled: true, isSelected: true },
        { label: '数量', prop: 'jadeQuantity', width: '60', isSelected: true },
        { label: '成本价', prop: 'jadeCost', width: '60', isSelected: true },
        { label: '标签价', prop: 'jadeTagPrice', Width: '60', isSelected: false },
        { label: '供应商', prop: 'supplierName', width: '70', isSelected: true },
        { label: '货品状态', prop: 'inventoryStatus', width: '70', isSelected: true },
        { label: '客户名字', prop: 'clientName', width: '70', isSelected: false },
        { label: '入库仓库', prop: 'warehouseName', width: '70', isSelected: false },
        { label: '入库类型', prop: 'orderType', width: '90', isdisabled: true, isSelected: true },
        { label: '入库人员', prop: 'createBy', width: '90', isdisabled: true, isSelected: true },
        { label: '入库时间', prop: 'createTime', minWidth: '100', isdisabled: true, isSelected: true },
        { label: '备注', prop: 'remark', minWidth: '80', maxWidth: '80', isSelected: true },
      ]
    })
    const inboundForm = reactive({  //入库表单数据
      wms_inbound_type: '',
      orderCode: '',
      barcode: '',//条形码
      jadeQuantity: 0,
      jades: [],
      desStorageId: "",
      desWarehouseId: "",
      supplierId: '',
      clientId: '',
      deptId: "1",
      remark: '',
    })
    const tempData = ref([])
    const dialogVisibleResult = ref(false)

    const clientList = ref([
    ])
    const warehouseList = ref([
    ])
    const imgsList = ref([//图像列表

    ])
    const dialogVisible1 = ref(false)//添加供应商

    const labelType = ref('phone')

    //表格用到的参数
    const state = reactive({
      data: {
        page: 1,
        limit: 10,
        total: inboundJadeInfoData.value.length,
      }
    });
    //前端限制分页（tableData为当前展示页表格）
    const tableData = () => {
      return inboundJadeInfoData.value
    };
    //改变页码
    const handleCurrentChange = (e) => {
      state.page = e;
    };
    //改变页数限制
    const handleSizeChange = (e) => {
      state.limit = e;
    };

    const articleOrgRef = ref(null)

    onBeforeMount(() => {//获取数据
      token.value = getToken()
      getCascader()
      getWarehouseListV2().then((res) => {
        warehouseList.value = res.rows
      })
      getClientList().then((res) => {
        clientList.value = res.rows
      })
    })

    onMounted(() => {    //周期函数  生成条形码
      tableFilter.data.forEach(function (item, index) {
        if (item.isSelected) {
          selectedFilters.data.push(item.label)
          inboundJadeDataColumn.data.push(item)
        }
      })
    })

    const filterColumns = () => {//监听筛选器，实现列的动态增删
      let temp = []
      tableFilter.data.forEach(item_t => {
        selectedFilters.data.forEach(item_s => {
          if (item_t.label == item_s) {
            temp.push(item_t)
          }

        })
      })
      inboundJadeDataColumn.data = temp
    }

    const getParentStorage = (val) => {
      console.log(val)
      for (const item of treeList.value) {//第一层
        if (item.id == val) {
          inboundForm.desStorageId = item.value
          inboundForm.desWarehouseId = item.id
        }
        if (item.childrenStorages.length != 0) {//递归往下
          if (findLabelByValue(item.childrenStorages, val)) {
            inboundForm.desWarehouseId = findLabelByValue(item.childrenStorages, val)
            console.log(inboundForm.desStorageId, inboundForm.desWarehouseId)
            return
          }
        }
      }
    }

    function findLabelByValue(tree, targetValue) {
      for (const node of tree) {
        if (node.id == targetValue) {
          inboundForm.desStorageId = node.id
          return node.parentWarehouse
        }
        if (Array.isArray(node.children)) {
          const value = findLabelByValue(node.children, targetValue);
          if (value) {
            return value
          }
        }
      }
      return null
    }
    const takePhoto = () => { //调用摄像头后拍照
      const video = videoElement.value
      const canvas = canvasElement.value
      if (cameraActive.value) {
        if (video) try {
          // 将视频画面绘制到画布上
          const context = canvas.getContext('2d');
          // canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height)
          const devicePixelRatio = window.devicePixelRatio || 1;
          // 设置 Canvas 元素的实际大小
          canvas.width = 2000 * devicePixelRatio;   // 宽度为 400 像素
          canvas.height = 1500 * devicePixelRatio;  // 高度为 300 像素
          // 缩放 Canvas 以适应屏幕
          context.scale(devicePixelRatio, devicePixelRatio);
          // 绘制一些内容
          context.fillStyle = 'red';
          context.drawImage(video, 0, 0, canvas.width, canvas.height);
          // 将画布内容转换为图片 URL
          // 将canvas内容转换为Blob对象
          canvas.toBlob(blob => {
            // 使用Blob对象创建URL
            const formData = new FormData()
            formData.append("file", blob, "image.png")
            // 使用 Axios 发送 POST 请求
            axios.post("http://8.134.106.197:9001/common/uploadImage", formData, {
              headers: {
                "Content-Type": "multipart/form-data",
                "Authorization": token.value,
              },
            }).then((res) => {
              getJadeCrop({ image_path: res.data.url.slice(34) }).then((res_crop) => {//分割图片
                if (res_crop.code == 500) {//是否分割出图片
                  ElMessage.error(res_crop)
                } else {
                  for (var key in res_crop.result) {
                    imageUrlList.value.push({ imageId: key, imageUrl: res_crop.result[key] })
                  }
                  let imageIds = imageUrlList.value.map(item => item.imageId)
                  getJadeFeature({ data: imageUrlList.value }).then(res => {
                    jadeMatch({ imageIds: imageIds }).then((res_match) => {
                      if (res_match.match_result == '') {
                        ElMessage.error('无法识别该货品')
                        imageUrlList.value = []
                      } else {
                        console.log(res_match.match_result)
                        imageUrlList.value = imageUrlList.value.map(item => {//放入匹配结果
                          const imageId = item.imageId;
                          const bestMatch = res_match.match_result[imageId];
                          console.log('匹配的图片' + bestMatch)
                          return { ...item, best_match: bestMatch };
                        })
                        getJadeInfo({ imageIds: imageUrlList.value.map(i => i.best_match) }).then((jadeInfos) => {//获取翡翠信息
                          jadeInfos.data.forEach(jade => {
                            imageUrlList.value.forEach(img => {
                              if (jade.imageId == img.best_match) {
                                img.matchUrl = jade.imageUrl
                                img.details = jade
                              }
                            })
                          })
                          console.log(imageUrlList.value)
                        })
                      }
                    })
                  })
                  dialogVisibleResult.value = true  //打开确认列表
                }
              })
            })
              .catch((error) => {
                // 处理上传失败的错误
                console.error(error)
              })
          });

        }
          catch (error) {
            console.log(error)
            ElMessage.error('摄像头拍照失败')
          }
      }
      else {
        ElMessage.error('请先打开摄像头')
      }

    };



    const triggerCamera = async () => { //启动摄像头

      if (cameraActive.value) {
        videoStream.value.getTracks().forEach(track => track.stop())//关闭摄像头代码
        videoElement.value.srcObject = null
        cameraActive.value = false
      } else {
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
          navigator.mediaDevices.getUserMedia({ video: true })
            .then(stream => {
              videoStream.value = stream
              videoElement.value.srcObject = stream
              cameraActive.value = true
            })
            .catch(error => {
              console.log(error)
              ElMessage.error('获取摄像头失败')
            });
        }
        else {
          ElMessage.error('获取摄像头失败，请检查是否已连接摄像头')
        }

      }
    };
    const handleUpload = (res) => {
      getJadeCrop({ image_path: res.url.slice(34) }).then((res_crop) => {//切割得到分割后的图列
        if (res_crop.code == 500) {//是否分割出图片
          ElMessage.error(res_crop)
        } else {
          for (var key in res_crop.result) {
            imageUrlList.value.push({ imageId: key, imageUrl: res_crop.result[key] })
          }
          let imageIds = imageUrlList.value.map(item => item.imageId)
          getJadeFeature({ data: imageUrlList.value }).then(res => {
            jadeMatch({ imageIds: imageIds }).then((res_match) => {
              if (res_match.match_result == '') {
                ElMessage.error('无法识别该货品')
                imageUrlList.value = []
              } else {
                console.log(res_match.match_result)
                imageUrlList.value = imageUrlList.value.map(item => {//放入匹配结果
                  const imageId = item.imageId;
                  const bestMatch = res_match.match_result[imageId];
                  console.log('匹配的图片' + bestMatch)
                  return { ...item, best_match: bestMatch };
                })
                getJadeInfo({ imageIds: imageUrlList.value.map(i => i.best_match) }).then((jadeInfos) => {//获取翡翠信息
                  jadeInfos.data.forEach(jade => {
                    imageUrlList.value.forEach(img => {
                      if (jade.imageId == img.best_match) {
                        img.matchUrl = jade.imageUrl
                        img.details = jade
                      }
                    })
                  })
                  console.log(imageUrlList.value)
                })
              }
            })
          })
          dialogVisibleResult.value = true  //打开确认列表
        }
      })
    }

    const handleDelteImg = (id) => {
      imageUrlList.value.forEach((item) => {
        if (item.imageId == id) {
          imageUrlList.value.pop(item)
        }
      })
    }

    const handlePictureCardPreview = (uploadFile) => {  //图片预览
      console.log(uploadFile)
      dialogImageUrl.value = uploadFile.url
      dialogVisibleImg.value = true
    }

    const cleanForm = () => { //重置表单
      console.log('清空表单')
      inbound.value.resetFields()
    }

    const previewSrcList = (imgUrl) => {//预览图片
      imgPreview.value = []
      imgPreview.value.push('http://47.106.116.146:8080/profile' + imgUrl)
    }
    const handleSelectionChange = (selection) => {
      selection.forEach((item) => {
        console.log(item.details)
        tempData.value.push(item.details)
      })
    }

    const ensureJade = () => {
      try {
        inboundJadeInfoData.value = tempData.value
        tempData.value = []
        imageUrlList.value = []
        dialogVisibleResult.value = false
      } catch {
        ElMessage.error('请检测完成后再勾选')
      }

    }

    const handleExpandChange = (val) => {
      inboundForm.desWarehouseId = val[0]
    }

    const handleNumberChange = () => {
      if (operation.value === 'floor') {
        inboundForm.jadeTagPrice = Math.floor(inboundForm.jadeCostPrice * rate.value);
      } else if (operation.value === 'ceil') {
        inboundForm.jadeTagPrice = Math.ceil(inboundForm.jadeCostPrice * rate.value);
      } else if (operation.value === 'round') {
        inboundForm.jadeTagPrice = Math.round(inboundForm.jadeCostPrice * rate.value);
      } else if (operation.value === 'toFixed') {
        inboundForm.jadeTagPrice = parseFloat((inboundForm.jadeCostPrice * rate.value).toFixed(1));
      }
    }

    watch(() => inboundForm.jadeCostPrice, (newValue) => {//成本价控制标签价
      if (operation.value == 'floor') {
        inboundForm.jadeTagPrice = Math.floor(newValue * rate.value);
      } else if (operation.value == 'ceil') {
        inboundForm.jadeTagPrice = Math.ceil(newValue * rate.value);
      } else if (operation.value == 'round') {
        inboundForm.jadeTagPrice = Math.round(newValue * rate.value);
      } else if (operation.value == 'toFixed') {
        inboundForm.jadeTagPrice = parseFloat((newValue * rate.value).toFixed(1));
      }
    });

    const onSubmit = () => {
      inboundForm.jades = inboundJadeInfoData.value
      inbounding(inboundForm).then(res => {
        if (res.code == 500) {
          ElMessage.error(res.msg)
        } else {
          inboundForm.clientId = inboundForm.desWarehouseId = inboundForm.jadeQuantity = ''
          ElMessage.success('还货成功')
        }

      })
    }

    const handleCloseResult = () => {
      imageUrlList.value = []
    }

    const cascaderHanlderChange = () => {
      console.log("label====", articleOrgRef.value.getCheckedNodes()[0].pathNodes)
      const pathArr = articleOrgRef.value.getCheckedNodes()[0].pathNodes
      const warehouseId = pathArr[0].data.warehouseId
      const cangweiId = pathArr[1].data.id
      inboundForm.desStorageId = cangweiId
      inboundForm.desWarehouseId = warehouseId
      console.log('inboundForm', inboundForm);
    }

    const getCascader = () => {
      getStorageCascader().then((res) => {
        treeList.value = res
        storageOptions.value = modifyData(res);
        filterDisableItem(storageOptions.value)
      })
    }

    function modifyData(data) {
      return Array.isArray(data) && data.map(warehouse => ({
        ...warehouse,
        storages: modifyStorages(warehouse.storages, warehouse.warehouseCode, warehouse.warehouseName),
      }));
    }

    function modifyStorages(storages, warehouseCode, warehouseName) {
      return storages.map(storage => ({
        ...storage,
        warehouseCode: storage.storageCode,
        warehouseName: storage.storageName,
      }));
    }
    // 添加 diabled 过滤属性
    function filterDisableItem(arr) {
      arr.forEach(item => {
        item.disabled = true
        if (item.warehouseStatus == '2' || item.warehouseStatus == '3') {
          item.storages.forEach(item => {
            item.disabled = true
          })
        }
      })
    }

    return {
      inboundForm, inboundRef, token, state, inboundJadeInfoData, inboundJadeDataColumn, selectedFilters,
      inboundOrderCode, imgPreview, dialogVisibleResult, match_controll, tempData,
      dialogVisible1, cameraActive, videoStream, dialogVisibleImg, dialogImageUrl, webcam,labelType,
      operation, rate, magnification, tableFilter, handleCloseResult,
      videoElement, canvasElement, imageUrlList, storageOptions, treeList,
      imgsList, clientList, warehouseList, tableData, filterColumns, getParentStorage, onSubmit, articleOrgRef,
      cleanForm, handleUpload, previewSrcList, handleDelteImg, ensureJade, handleSelectionChange, handleCurrentChange, handleSizeChange, cascaderHanlderChange,
      triggerCamera, takePhoto, handlePictureCardPreview, handleNumberChange, handleExpandChange,
      ...toRefs(state),
    };
  }
})
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.front {
  display: flex;
  height: 35%;

  .left {
    height: 100%;
    background-color: #fff;
    padding: 15px;
    display: flex;
    flex-direction: column;
    align-self: flex-start;
    gap: 30px;
    width: 58%;

    .left-input {
      float: auto;
      margin-bottom: 10px;
    }

    .left-end {}
  }

  .right {
    height: 100%;
    margin-left: 15px;
    background-color: #fff;
    padding: 15px;
    width: 40%;

    .right-photo {
      width: 100%;
      height: 80%;
      border: solid 1px;
    }


    .rigth-video {
      flex: auto;
      width: 440px;
      height: 180px;
    }

    .right-img {
      flex: auto;
      // width: 400px;
      // height: 500px;
      position: absolute;
      top: -9999px;
      opacity: 0;
    }

    .right-action {
      width: 100%;
      height: 40px;
      margin: 10px;

      .el-upload {
        display: inline-block;
      }
    }

  }
}



.tail {
  background-color: #fff;
  margin-top: 50px;
  padding: 10px;

  .tail-action {
    margin-bottom: 10px;
    display: flex;
  }
}
</style>
